package com.zxl.openapi.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zxl.openapi.constans.SystemParameter;
import com.zxl.openapi.feign.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * 用于过滤传递的参数的过滤器
 */
@Component
public class ParameterFilter extends ZuulFilter {

    @Autowired
    private RedisService redisService;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {

        Map<String, Map<Object, Object>> allApiInfoMap = SystemParameter.allApiInfoMap;

        RequestContext context = RequestContext.getCurrentContext();

        HttpServletRequest request = context.getRequest();

        String method = request.getParameter("method");

        System.out.println(method);
        //获取当前接口的map
        Map<Object, Object> map = allApiInfoMap.get(SystemParameter.REDIS_APIPRE + method);
        System.out.println(SystemParameter.REDIS_APIPRE + method);
        System.out.println(map);
        //获取当前过滤器需要经过的filters
        String filters = (String) map.get("filters");
        return context.sendZuulResponse() && filters != null && filters.contains(getClass().getName());

    }

    @Override
    public Object run() throws ZuulException {
        //我们需要判断参数有没有传递
        //实际上就是查看一下这个参数的值有没有
        //参数是什么,我们发现是动态的
        //每次需要获取一下看看当前需要过滤什么参数
        //因为我们的zuul是集群,所以将数据放到zuul之外的地方,redis就可以
        //参数在redis中存放的结构是什么
        //关于key是什么,此处我们是内部校验的,和用户身份已经请求地址无关,所以这个key我们可以直接在项目定义固定值
        RequestContext currentContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currentContext.getRequest();
        //从redis中获取需要传递的参数
        Set<String> commonsparameters = redisService.memebers("commonsparameters");

        for (String commonsparameter : commonsparameters) {

            String parameter = request.getParameter(commonsparameter);

            if(parameter == null || "".equalsIgnoreCase(parameter.trim())){
                //参数没传递
                currentContext.getResponse().setContentType("text/html;charset=utf-8");

                currentContext.setResponseBody("参数" +  commonsparameter + "不能为空");

                currentContext.setSendZuulResponse(false);

            }

        }

        return null;

    }
}
